import uuid
from django.db.models import Q
from rest_framework.decorators import api_view
from rest_framework.response import Response

from user.models import Staff
from utils.decorator_ import PermissionCheck
from .models import Dealer
from .serializer import DealerSerializer

@PermissionCheck('dealer.add_dealer')
@api_view(['post'])
def addDealer(request):
    """
        添加经销商
    :param request: 请求参数
    :data :post 请求参数字典
    :return:
    """
    dealer_id = uuid.uuid4().hex
    data = {key: request.data.get(key) for key in request.data}
    company = request.data.get('company')
    dealer = Dealer.objects.filter(company=company)
    if dealer:
        return Response({'msg': '该公司已经收录'})
    Dealer.objects.create(dealer_id=dealer_id, **data)
    return Response({'msg': '添加成功'})

@PermissionCheck('dealer.delete_dealer')
@api_view(['get'])
def delDealer(request):
    """
        删除经销商，在后台修改经销商的状态
    :param request:
    :return:
    """
    dealer = Dealer.objects.get(pk=request.GET.get('dealer'))
    if dealer.status in ['已解约', '']:
        return Response({'msg': "公司已解约或不存在"})
    if dealer:
        dealer.status = '已解约'
        dealer.save()
        return Response({
            'msg': '经销商删除成功'
        })
    else:
        return Response({'msg': '经销商不存在'})

@PermissionCheck('dealer.change_dealer')
@api_view(['put'])
def alterDealer(request):
    data = {key: request.data.get(key) for key in request.data}
    d = Dealer(**data)
    d.save()
    return Response({'msg': '修改成功'})

@PermissionCheck('dealer.view_dealer')
@api_view(['get'])
def findDealerAll(request):
    print('---request user---', request.user)
    name = Staff.objects.get(pk=request.user.pk).role.name
    if name in ['总经理', '仓库经理']:
        qs = Dealer.objects.filter(status='正常')
        qs1 = Dealer.objects.filter(~Q(status='正常'))
        ret = DealerSerializer(qs, many=True)
        ret1 = DealerSerializer(qs1, many=True)
        return Response({'合同期内': ret.data, '终止合约': ret1.data})
    elif name == '业务经理':
        qs = Dealer.objects.filter(Q(Q(staff_id=request.user.staff_id) & Q(status='正常')))
        ret = DealerSerializer(qs, many=True)
        return Response(ret.data)
    else:
        return Response({'msg': '您再看一眼试试，戳瞎你的眼！'})
